package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理器
@RestControllerAdvice
@Slf4j
public class GlobalExpectionHandler {
//    @ExceptionHandler
//    public Result handlerException(Exception e) {
//        log.error("错误", e);
//        return Result.error("您当前网络波动较大, 请稍后重试!");
//    }

    @ExceptionHandler
    public Result duplicateFileldException(DuplicateKeyException e) {
        log.error("程序错误", e);
        String message = e.getMessage();
        //捕获duplicate第一次出现的索引
        int index = message.indexOf("duplicate entry");
        String substring = message.substring(index);
        String[] strings = substring.split("");
        String duplicate = strings[2];
        return Result.error(duplicate + "重复");

    }


}

